<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<style>
    .announcement-card {
        position: absolute;
        top: 100%;
        right: 0;
        width: 350px;
        max-height: 500px;
        background: white;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 1050;
        margin-top: 8px;
        overflow: hidden;
    }
    .announcement-card-header {
        padding: 12px 16px;
        border-bottom: 1px solid #dee2e6;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f8f9fa;
    }
    .announcement-card-body {
        max-height: 400px;
        overflow-y: auto;
        padding: 0;
    }
    .announcement-item {
        padding: 12px 16px;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    .announcement-item:hover {
        background-color: #f8f9fa;
    }
    .announcement-item:last-child {
        border-bottom: none;
    }
    .announcement-title {
        font-weight: 600;
        color: #212529;
        margin-bottom: 4px;
        font-size: 14px;
    }
    .announcement-content {
        color: #6c757d;
        font-size: 12px;
        margin-bottom: 4px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
    .announcement-time {
        color: #adb5bd;
        font-size: 11px;
    }
    .announcement-empty {
        padding: 40px 20px;
        text-align: center;
        color: #6c757d;
    }
    #announcementIcon:hover {
        opacity: 0.8;
    }
    .navbar {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1030;
        width: 100%;
    }
    body {
        padding-top: 56px;
    }
</style>
<nav class="navbar navbar-expand-lg navbar-dark bg-success">
    <div class="container-fluid">
        <a class="navbar-brand" href="${pageContext.request.contextPath}/merchant/index">助农购物 - 商户端</a>
        <div class="navbar-nav ms-auto d-flex align-items-center">
            <!-- 公告图标 -->
            <div class="nav-item position-relative me-3 d-flex align-items-center" id="announcementContainer">
                <a class="nav-link d-inline-flex align-items-center" href="javascript:void(0)" id="announcementIcon" style="cursor: pointer; padding: 0.5rem;">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-bell" viewBox="0 0 16 16">
                        <path d="M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zM8 1.918l-.797.161A4.002 4.002 0 0 0 4 6c0 .628-.134 1.197-.448 1.742-.448.72-.973 1.135-1.552 1.135h-.448c-.179 0-.322.144-.322.323v.792c0 .18.143.323.322.323h11.112c.18 0 .322-.144.322-.323v-.792c0-.18-.143-.323-.322-.323h-.448c-.58 0-1.104-.415-1.552-1.135C12.134 7.197 12 6.628 12 6a4.002 4.002 0 0 0-3.203-3.92L8 1.917zM14.22 12c.223.447.481.801.78 1H1c.299-.199.557-.553.78-1C2.68 10.2 3 6.88 3 6c0-2.42 1.72-4.44 4.005-4.901a1 1 0 1 1 1.99 0A5.002 5.002 0 0 1 13 6c0 .88.32 4.2 1.22 6z"/>
                    </svg>
                    <span class="badge bg-danger position-absolute top-0 start-100 translate-middle" id="announcementBadge" style="display: none; font-size: 0.6rem;">0</span>
                </a>
                <!-- 公告卡片 -->
                <div class="announcement-card" id="announcementCard" style="display: none;">
                    <div class="announcement-card-header">
                        <h6 class="mb-0">公告通知</h6>
                        <button type="button" class="btn-close btn-close-sm" id="closeAnnouncementCard"></button>
                    </div>
                    <div class="announcement-card-body" id="announcementList">
                        <div class="text-center text-muted py-3">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <div class="mt-2">加载中...</div>
                        </div>
                    </div>
                </div>
            </div>
            <ul class="navbar-nav">
                <li class="nav-item dropdown d-flex align-items-center">
                    <a class="nav-link dropdown-toggle d-flex align-items-center" href="javascript:void(0)" id="merchantDropdown" role="button" 
                       data-bs-toggle="dropdown" aria-expanded="false" aria-haspopup="true" style="height: 100%;">
                        ${sessionScope.merchant.realName != null && !empty sessionScope.merchant.realName ? sessionScope.merchant.realName : sessionScope.merchant.username}
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="merchantDropdown">
                        <li><a class="dropdown-item" href="${pageContext.request.contextPath}/merchant/user/profile">个人中心</a></li>
                        <li><a class="dropdown-item" href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#changePasswordModal" onclick="event.stopPropagation();">修改密码</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="${pageContext.request.contextPath}/logout">退出登录</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<!-- 修改密码模态框 -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changePasswordModalLabel">修改密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="changePasswordForm" onsubmit="return false;">
                    <div class="mb-3">
                        <label for="oldPassword" class="form-label">当前密码</label>
                        <input type="password" class="form-control" id="oldPassword" name="oldPassword" 
                               placeholder="请输入当前密码" required
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="oldPasswordError"></div>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">新密码</label>
                        <input type="password" class="form-control" id="newPassword" name="newPassword" 
                               placeholder="请输入新密码（至少6位）" required minlength="6"
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="newPasswordError"></div>
                    </div>
                    <div class="mb-3">
                        <label for="confirmPassword" class="form-label">确认密码</label>
                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" 
                               placeholder="请再次输入新密码" required minlength="6"
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="confirmPasswordError"></div>
                    </div>
                    <div class="alert alert-danger d-none" id="changePasswordError"></div>
                    <div class="alert alert-success d-none" id="changePasswordSuccess"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="changePasswordSubmitBtn">确认修改</button>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    // 确保Bootstrap下拉菜单初始化
    function initDropdowns() {
        if (typeof bootstrap === 'undefined' || !bootstrap.Dropdown) {
            setTimeout(initDropdowns, 50);
            return;
        }
        
        var dropdownElementList = document.querySelectorAll('.dropdown-toggle');
        dropdownElementList.forEach(function (dropdownToggleEl) {
            try {
                var dropdownInstance = bootstrap.Dropdown.getInstance(dropdownToggleEl);
                if (!dropdownInstance) {
                    new bootstrap.Dropdown(dropdownToggleEl);
                }
            } catch (e) {
                console.error('初始化下拉菜单失败:', e);
            }
        });
    }
    
    // 初始化修改密码功能
    function initChangePassword() {
        var changePasswordBtn = document.getElementById('changePasswordSubmitBtn');
        if (changePasswordBtn) {
            changePasswordBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                var oldPasswordInput = document.getElementById('oldPassword');
                var newPasswordInput = document.getElementById('newPassword');
                var confirmPasswordInput = document.getElementById('confirmPassword');
                
                if (!oldPasswordInput || !newPasswordInput || !confirmPasswordInput) {
                    console.error('找不到密码输入框');
                    return;
                }
                
                var oldPassword = oldPasswordInput.value.trim();
                var newPassword = newPasswordInput.value.trim();
                var confirmPassword = confirmPasswordInput.value.trim();
                
                var errorDiv = document.getElementById('changePasswordError');
                var successDiv = document.getElementById('changePasswordSuccess');
                
                // 清除之前的消息和验证状态
                if (errorDiv) errorDiv.classList.add('d-none');
                if (successDiv) successDiv.classList.add('d-none');
                oldPasswordInput.classList.remove('is-invalid');
                newPasswordInput.classList.remove('is-invalid');
                confirmPasswordInput.classList.remove('is-invalid');
                
                // 验证输入
                var isValid = true;
                
                if (!oldPassword) {
                    oldPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('oldPasswordError');
                    if (errorMsg) errorMsg.textContent = '请输入当前密码';
                    isValid = false;
                }
                
                if (!newPassword) {
                    newPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('newPasswordError');
                    if (errorMsg) errorMsg.textContent = '请输入新密码';
                    isValid = false;
                } else if (newPassword.length < 6) {
                    newPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('newPasswordError');
                    if (errorMsg) errorMsg.textContent = '新密码长度至少6位';
                    isValid = false;
                }
                
                if (!confirmPassword) {
                    confirmPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('confirmPasswordError');
                    if (errorMsg) errorMsg.textContent = '请确认新密码';
                    isValid = false;
                } else if (newPassword !== confirmPassword) {
                    confirmPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('confirmPasswordError');
                    if (errorMsg) errorMsg.textContent = '新密码和确认密码不一致';
                    isValid = false;
                }
                
                if (!isValid) {
                    if (errorDiv) {
                        errorDiv.textContent = '请检查输入信息';
                        errorDiv.classList.remove('d-none');
                    }
                    return;
                }
                
                // 禁用按钮
                var submitBtn = document.getElementById('changePasswordSubmitBtn');
                submitBtn.disabled = true;
                submitBtn.textContent = '修改中...';
                
                // 发送AJAX请求
                var params = new URLSearchParams();
                params.append('oldPassword', oldPassword);
                params.append('newPassword', newPassword);
                params.append('confirmPassword', confirmPassword);
                
                fetch('${pageContext.request.contextPath}/merchant/user/changePassword', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: params.toString()
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (successDiv) {
                            successDiv.textContent = data.message;
                            successDiv.classList.remove('d-none');
                        }
                        
                        // 清空表单
                        oldPasswordInput.value = '';
                        newPasswordInput.value = '';
                        confirmPasswordInput.value = '';
                        
                        // 3秒后关闭模态框
                        setTimeout(function() {
                            var modal = bootstrap.Modal.getInstance(document.getElementById('changePasswordModal'));
                            if (modal) modal.hide();
                        }, 2000);
                    } else {
                        if (errorDiv) {
                            errorDiv.textContent = data.message;
                            errorDiv.classList.remove('d-none');
                        }
                    }
                })
                .catch(error => {
                    if (errorDiv) {
                        errorDiv.textContent = '修改密码失败，请重试';
                        errorDiv.classList.remove('d-none');
                    }
                })
                .finally(() => {
                    submitBtn.disabled = false;
                    submitBtn.textContent = '确认修改';
                });
            });
        }
        
        // 模态框关闭时清除表单和消息
        var changePasswordModal = document.getElementById('changePasswordModal');
        if (changePasswordModal) {
            changePasswordModal.addEventListener('hidden.bs.modal', function() {
                document.getElementById('changePasswordForm').reset();
                document.getElementById('changePasswordError').classList.add('d-none');
                document.getElementById('changePasswordSuccess').classList.add('d-none');
                document.getElementById('oldPassword').classList.remove('is-invalid');
                document.getElementById('newPassword').classList.remove('is-invalid');
                document.getElementById('confirmPassword').classList.remove('is-invalid');
            });
        }
    }
    
    // 初始化公告功能
    function initAnnouncement() {
        <c:if test="${sessionScope.merchant != null}">
        var announcementIcon = document.getElementById('announcementIcon');
        var announcementCard = document.getElementById('announcementCard');
        var announcementList = document.getElementById('announcementList');
        var announcementBadge = document.getElementById('announcementBadge');
        var closeBtn = document.getElementById('closeAnnouncementCard');
        var isCardVisible = false;
        var announcementsLoaded = false;
        
        // 页面加载时立即加载公告数量（用于显示角标）
        loadAnnouncementCount();
        
        // 点击图标显示/隐藏卡片
        if (announcementIcon) {
            announcementIcon.addEventListener('click', function(e) {
                e.stopPropagation();
                toggleAnnouncementCard();
            });
        }
        
        // 关闭按钮
        if (closeBtn) {
            closeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                hideAnnouncementCard();
            });
        }
        
        // 点击外部区域关闭卡片
        document.addEventListener('click', function(e) {
            var container = document.getElementById('announcementContainer');
            if (container && !container.contains(e.target) && isCardVisible) {
                hideAnnouncementCard();
            }
        });
        
        // 鼠标悬浮显示卡片
        if (announcementIcon) {
            announcementIcon.addEventListener('mouseenter', function() {
                if (!isCardVisible) {
                    showAnnouncementCard();
                }
            });
        }
        
        if (announcementCard) {
            announcementCard.addEventListener('mouseleave', function() {
                hideAnnouncementCard();
            });
        }
        
        function toggleAnnouncementCard() {
            if (isCardVisible) {
                hideAnnouncementCard();
            } else {
                showAnnouncementCard();
            }
        }
        
        function showAnnouncementCard() {
            if (announcementCard) {
                announcementCard.style.display = 'block';
                isCardVisible = true;
                
                // 如果还没加载过，加载公告列表
                if (!announcementsLoaded) {
                    loadAnnouncements();
                }
            }
        }
        
        function hideAnnouncementCard() {
            if (announcementCard) {
                announcementCard.style.display = 'none';
                isCardVisible = false;
            }
        }
        
        // 加载公告数量（用于显示角标）
        function loadAnnouncementCount() {
            fetch('${pageContext.request.contextPath}/merchant/announcement/listAjax')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data && data.data.length > 0) {
                        // 更新徽章
                        if (announcementBadge) {
                            announcementBadge.textContent = data.data.length;
                            announcementBadge.style.display = 'inline-block';
                        }
                    }
                })
                .catch(error => {
                    console.error('加载公告数量失败:', error);
                });
        }
        
        function loadAnnouncements() {
            if (announcementsLoaded) return;
            
            fetch('${pageContext.request.contextPath}/merchant/announcement/listAjax')
                .then(response => response.json())
                .then(data => {
                    announcementsLoaded = true;
                    if (data.success && data.data) {
                        displayAnnouncements(data.data);
                        // 更新徽章（如果还没有显示）
                        if (announcementBadge && data.data.length > 0) {
                            announcementBadge.textContent = data.data.length;
                            announcementBadge.style.display = 'inline-block';
                        }
                    } else {
                        displayEmpty();
                    }
                })
                .catch(error => {
                    console.error('加载公告失败:', error);
                    displayEmpty();
                });
        }
        
        function displayAnnouncements(announcements) {
            if (!announcementList) return;
            
            if (announcements.length === 0) {
                displayEmpty();
                return;
            }
            
            var html = '';
            announcements.forEach(function(ann) {
                html += '<div class="announcement-item">';
                html += '<div class="announcement-title">' + escapeHtml(ann.title) + '</div>';
                html += '<div class="announcement-content">' + escapeHtml(ann.content) + '</div>';
                html += '<div class="announcement-time">' + ann.createTime + '</div>';
                html += '</div>';
            });
            
            announcementList.innerHTML = html;
        }
        
        function displayEmpty() {
            if (!announcementList) return;
            announcementList.innerHTML = '<div class="announcement-empty">暂无公告</div>';
        }
        
        function escapeHtml(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        </c:if>
    }
    
    // DOM加载完成后初始化
    function initAll() {
        initDropdowns();
        initChangePassword();
        initAnnouncement();
    }
    
    // 等待页面加载完成和Bootstrap JS加载
    function waitForBootstrap() {
        if (typeof bootstrap !== 'undefined' && bootstrap.Dropdown) {
            initAll();
        } else {
            setTimeout(waitForBootstrap, 50);
        }
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', waitForBootstrap);
    } else {
        waitForBootstrap();
    }
})();
</script>
